package com.swt.gap.config.shiro;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.ehcache.EhCacheManager;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * created by lanshengyuan on 2019/10/29
 * @author 蓝将军
 */
public class CustomCredentialsMatcher extends HashedCredentialsMatcher {

    private int maxRetryNum = 3;

    private EhCacheManager shiroEhcacheManager;


    public void setMaxRetryNum(int maxRetryNum) {
        this.maxRetryNum = maxRetryNum;
    }

    /**
     * 构造方法 创建对象,传入缓存的管理器
     */
    public CustomCredentialsMatcher(EhCacheManager shiroEhcacheManager) {
        this.shiroEhcacheManager = shiroEhcacheManager;
    }

    /**
     *  用户登录错误次数方法.
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token,AuthenticationInfo info) {

        Cache<String, AtomicInteger> passwordRetryCache = shiroEhcacheManager.getCache("passwordRetryCache");

        //获取用户名并做key
        String key = (String) token.getPrincipal();

        if (null != key) {
            //retry count + 1
            AtomicInteger retryCount = passwordRetryCache.get(key);
            if (null == retryCount) {
                retryCount = new AtomicInteger(0);
                passwordRetryCache.put(key, retryCount);
            }
            /*if (retryCount.incrementAndGet() > maxRetryNum) {
                throw new ExcessiveAttemptsException("username: " + key + " tried to login more than 3 times in period");
            }*/
        }
        boolean matches = super.doCredentialsMatch(token, info);
        if (matches) {
            //clear retry data
            passwordRetryCache.remove(key);
        }
        return matches;
    }
}
